package ray.mgocc.net;

import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import ray.mgocc.PlayerCharacter;
import ray.mgocc.Source;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RecordPage{
    private final static Log log = LogFactory.getLog(RecordPage.class);

    private PlayerCharacter pc = null;
    private Agent agent = null;
    public final static int TAB_TOTAL = 0;
    public final static int TOTAL = 0;
    public final static int WEEK = 1;
    public RecordPage(Agent agent,PlayerCharacter pc){
        setAgent(agent);
        setPlayerCharacter(pc);
    }
    private void setPlayerCharacter(PlayerCharacter pc){
        this.pc = pc;
    }
    private PlayerCharacter getPlayerCharacter(){
        return this.pc;
    }
    private void setAgent(Agent agent){
        this.agent = agent;
    }
    private Request getRequest(int term,int tab){
        String name = "record"+term+"_"+tab+".html";
        Request request = new Request(CommunitySupportPage.URI,name);
        request.addParam("m","pc");
        request.addParam("a","page_fh_playerscore");
        request.addParam("target_c_member_id",
                         Integer.toString(getPlayerCharacter().getNumber()));
        request.addParam("tabid",Integer.toString(tab));
        request.addParam("term",Integer.toString(term));

        return request;
    }
    public List<Source> getAll(){
        List list = new ArrayList();
        for(int term=0;term<=1;term++){
            for(int tab=0;tab<=15;tab++){
                list.add(get(term,tab));
            }
        }
        return list;
    }
    public Source get(int term,int tab){
        Request request = getRequest(term,tab);
        Source in = null;
        in = agent.request(request);
        check(in.getStream());
        return in;
    }
    private final static Pattern error = Pattern.compile("(change_resolution_for_top|do_o_select_player)");
    private static boolean check(String body){
        if(error.matcher(body).find()){
            throw new RuntimeException("response is contain illegal message.");
        }
        return true;
    }
    private static boolean check(InputStream in){
        BufferedReader buf = new BufferedReader(new InputStreamReader(in));
        String line;
        try{
            while(null!=(line=buf.readLine())){
                check(line);
            }
        }catch(IOException e){
            throw new RuntimeException("can not check.",e);
        }
        return true;
    }
}

